package com.origin.app.service

import android.app.Activity
import android.app.Service
import android.content.Intent
import android.os.IBinder
import android.os.Message
import android.util.Log
import androidx.core.content.ContextCompat
import com.google.gson.Gson
import com.jeremyliao.liveeventbus.LiveEventBus
import com.microsoft.signalr.Action1
import com.microsoft.signalr.HubConnection
import com.microsoft.signalr.HubConnectionBuilder
import com.microsoft.signalr.HubConnectionState
import com.origin.app.bean.BaseNetBean
import com.origin.app.bean.CompanyBean
import com.origin.app.bean.CompanyPointBean
import com.origin.app.bean.MessageBean
import com.origin.app.utils.UserInfoUtils
import com.origin.utils.gson.GsonUtils
import com.origin.utils.log.LogUtils
import ikidou.reflect.TypeBuilder
import io.reactivex.Single
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.util.concurrent.TimeUnit

class SignalrService : Service() {

    companion object {
        fun launcher(activity: Activity) {
            val serviceIntent = Intent(activity, SignalrService::class.java)
            activity.startService(serviceIntent)
        }

        fun addGroups(activity: Activity, list: MutableList<String>) {
            val serviceIntent = Intent(activity, SignalrService::class.java)
            serviceIntent.putExtra("activeType", 1)
            serviceIntent.putStringArrayListExtra("data", ArrayList(list))
            activity.startService(serviceIntent)
        }
    }

    val LOCATE_EVENT = "CRAB_IM_ON_LOCATE_MESSAGE";

    override fun onBind(p0: Intent?): IBinder? {
        return null;
    }

    private var scope = CoroutineScope(Dispatchers.Default)
    override fun onCreate() {
        super.onCreate()
        LogUtils.__e("SignalrService  ===   onCreate")
        connectHubConnection();
    }

    var companyCodeList: MutableList<String> = mutableListOf()
    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        if (intent == null) {
            return START_NOT_STICKY
        }
        val activeType = intent.getIntExtra("activeType", 0)
        if (activeType == 1) {
            val data: ArrayList<String>? = intent.getStringArrayListExtra("data")
            if (data == null || data.size == 0) {
                return START_NOT_STICKY
            }
            addGroups(data)
        }
        return super.onStartCommand(intent, flags, startId)
    }

    private var hubConnection: HubConnection? = null
    private fun connectHubConnection() {
        // uid为用户id type学员为1 管理员为2

        hubConnection =
            HubConnectionBuilder.create("http://132.232.253.210:25112/chatHub?uid=335&type=2")
                .withAccessTokenProvider(Single.defer<String> {
                    Single.just<String>(
                        UserInfoUtils.getUserInfo().session_token
                    )
                }).build()
        hubConnection?.serverTimeout = (4 * 60 * 1000).toLong() //超时
        hubConnection?.keepAliveInterval = (2 * 60 * 1000).toLong() //心跳
        startConnect(null)
        hubConnection?.on<Any>(
            "Message",
            Action1<Any?> { param1 ->
                var json = param1.toString()
                try {
                    val type = TypeBuilder.newInstance(MessageBean::class.java)
                        .addTypeParam(CompanyPointBean::class.java)
                        .build()
                    var messageBean = GsonUtils.gson.fromJson<MessageBean<CompanyPointBean>>(json, type)
//                    LogUtils.__e("消息类型 ===> ${messageBean.data.equipmentState}")
                    LiveEventBus.get<CompanyPointBean>(messageBean.type).post(messageBean.data);
                }catch (e:Exception){
                    Log.e("接受消息", e.toString())
                }

            }, Any::class.java
        )
    }

    private fun startConnect(data: ArrayList<String>?) {
        scope.launch {
            val isConnected = withContext(Dispatchers.IO) {
                val isConnected: Boolean = hubConnection?.start()
                    ?.blockingAwait(
                        (6000 * 10).toLong(),
                        TimeUnit.MILLISECONDS
                    ) == true //启动链接，设置超时6000*10，毫秒级；会有阻塞所以开线程
                return@withContext isConnected
            }
            LogUtils.__e("结果===> isConnected ${isConnected}")
            if (isConnected&& data!=null&& data.size>0) {
                addGroups(data)
            }
        }
    }

    private fun addGroups(data: ArrayList<String>) {
        if (hubConnection == null) {
            return;
        }

        val connectionState: HubConnectionState = hubConnection!!.connectionState;
        if (connectionState == HubConnectionState.DISCONNECTED) {
            startConnect(data);
            return
        }
        companyCodeList.forEach {
            hubConnection?.invoke("ReomveGroup", it);
        }
        companyCodeList.clear()
        companyCodeList.addAll(data)
        companyCodeList.forEach {
            hubConnection?.invoke("AddGroup", it);
        }
    }


}